<?php

namespace app\common\model\wanlshop;

use think\Model;


class Settlement extends Model
{

    

    

    // 表名
    protected $name = 'wanlshop_settlement';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'way_text',
        'status_text',
        'successtime_text'
    ];
    

    
    public function getWayList()
    {
        return ['auto' => __('Way auto'), 'admin' => __('Way admin')];
    }

    public function getStatusList()
    {
        return ['created' => __('Status created'), 'success' => __('Status success'), 'lock' => __('Status lock')];
    }


    public function getWayTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['way']) ? $data['way'] : '');
        $list = $this->getWayList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getSuccesstimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['successtime']) ? $data['successtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setSuccesstimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function shop()
    {
        return $this->belongsTo('app\admin\model\wanlshop\Shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function admin()
    {
        return $this->belongsTo('app\admin\model\Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function package()
    {
        return $this->belongsTo('app\api\model\wanlshop\Package', 'package_no', 'package_no', [], 'LEFT')->setEagerlyType(0);
    }

    //放入结算记录
    public function putRecord($price,$shop,$order_no,$package_no,$memo){
        $settlement = $this->create([
            'shop_id' => $shop['id'],
            'order_no' => $order_no,
            'package_no' => $package_no,
            'price' => $price,
            'way' => 'admin',
            'memo' => $memo,
        ]);
        if($shop['state'] == 1){
            $settlement->way = 'auto';
            $settlement->status = 'success';
            $settlement->successtime = time();
            $settlement->save();
            //$this->settlement($price,$shop['user_id'],$memo,'settlement',$order_no);
        }
    }

    //结算
    public function settlement($price,$user_id,$memo,$type,$ids){
        controller('addons\wanlshop\library\WanlPay\WanlPay')->money($price, $user_id, $memo, $type, $ids);
    }
}
